package hu.jonas.allunit;

import hu.jonas.allunit.AllUnitPlugin;
import hu.jonas.allunit.model.TestResultModel;
import hu.jonas.allunit.nature.AllUnitNature;
import hu.jonas.allunit.views.AllUnitViewPart;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
import org.eclipse.jdt.junit.JUnitCore;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;

@SuppressWarnings("restriction")
public class PluginHelper {

	public IJavaElement create(IFile file) {
		return JavaCore.create(file);
	}
	
	public IJavaProject create(IProject project) {
		return JavaCore.create(project);
	}

	public IJavaModel create(IWorkspaceRoot workspaceRoot) {
		return JavaCore.create(workspaceRoot);
	}
	
	public IType[] findTestTypes(IJavaElement container, IProgressMonitor monitor)
			throws OperationCanceledException, CoreException {
		return JUnitCore.findTestTypes(container, monitor);
	}
	
	public IJavaProject[] getAllJavaProjects() throws JavaModelException {
		return create(getWorkspace().getRoot()).getJavaProjects();
	}
	
	public AllUnitViewPart getAllUnitView() {
		return (AllUnitViewPart) PlatformUI.getWorkbench()
			.getWorkbenchWindows()[0].getPages()[0].findView(AllUnitViewPart.VIEWPART_ID);
	}
	
	public Display getDefaultDisplay() {
		return Display.getDefault();
	}
	
	public String getPluginID() {
		return AllUnitPlugin.PLUGIN_ID;
	}
	
	public TestResultModel getTestResultModel() {
		return AllUnitPlugin.getTestResultModel();
	}
	
	public IWorkspace getWorkspace() {
		return ResourcesPlugin.getWorkspace();
	}
	
	public boolean hasJavaProjectAllUnitNature(IJavaProject javaProject) throws CoreException {
		String[] natureIds = javaProject.getProject().getDescription().getNatureIds();
		
		for (int i = 0; i < natureIds.length; i++) {
			if (AllUnitNature.ID.equals(natureIds[i])) {
				return true;
			}
		}
		
		return false;
	}
	
	public boolean isTestOrTestSuite(IType type) throws CoreException {
		return TestSearchEngine.isTestOrTestSuite(type);
	}

	public void logInfo(String format, Object... args) {
		AllUnitPlugin.logInfo(String.format(format, args));
	}
}
